using UnityEngine;
using System.Collections;

[System.Serializable]
public class MoveEyes : MonoBehaviour {
	
	public Transform[] eyes;
	public Transform objectToMoveEyesTowards;
	public bool lockX = false;
	public bool lockY = false;
	public bool lockZ = false;	
	public float maxDistanceToMove = 1.0f;
	public bool debug = false;
	public float threshold = 0.6f;
	
	private Vector3[] startPos;
	private bool triggered = false;
	
	// Use this for initialization
	void Start () {
	}
	
	// Update is called once per frame
	void Update () {
		if (triggered) {
			foreach (Transform t in eyes) {
				Vector3 newLocalPos = t.localPosition;
				Vector3 newPos = t.position;
				bool isPastBorder = false;
				if (!lockX) {
					if (t.localPosition.x <	maxDistanceToMove) {
						newPos.x = objectToMoveEyesTowards.position.x - threshold;
					} else if (t.localPosition.x > -(maxDistanceToMove)) {
						newPos.x = objectToMoveEyesTowards.position.x + threshold;
					} else if (t.localPosition.x > maxDistanceToMove){
						newLocalPos.x = maxDistanceToMove;
						isPastBorder = true;
					} else if (t.localPosition.x < -(maxDistanceToMove)) {
						newLocalPos.x = -(maxDistanceToMove);
						isPastBorder = true;
					}
				}
				if (!lockY) {
					if (t.localPosition.y <	maxDistanceToMove) {
						newPos.y = objectToMoveEyesTowards.position.y - threshold;
					} else if (t.localPosition.x > -(maxDistanceToMove)) {
						newPos.y = objectToMoveEyesTowards.position.y + threshold;
					}  else if (t.localPosition.y > maxDistanceToMove){
						newLocalPos.y = maxDistanceToMove;
						isPastBorder = true;
					} else if (t.localPosition.y < -(maxDistanceToMove)) {
						newLocalPos.y = -(maxDistanceToMove);
						isPastBorder = true;
					}
				}
				if (!lockZ) {
					if (t.localPosition.z <	maxDistanceToMove) {
						newPos.z = objectToMoveEyesTowards.position.z - threshold;
					} else if (t.localPosition.z > -(maxDistanceToMove)) {
						newPos.z = objectToMoveEyesTowards.position.z + threshold;
					} else if (t.localPosition.z > maxDistanceToMove){
						newLocalPos.z = maxDistanceToMove;
						isPastBorder = true;
					} else if (t.localPosition.z < -(maxDistanceToMove)) {
						newLocalPos.z = -(maxDistanceToMove);
						isPastBorder = true;
					}
				}
				
				if (isPastBorder) {
					t.localPosition = newLocalPos;	
				} else {
					t.position = newPos;	
				}
			}
		}
	}
	
	void OnTriggerEnter(Collider other) {
		if (other.tag == "Player") 	{
			triggered = true;	
		}
	}
	
	void OnTriggerExit(Collider other) {
		if (other.tag == "Player") 	{
			triggered = false;	
		}	
	}
	
	void OnGUI() {
		if (debug) {
			GUI.Box(new Rect(100, 100, 200, 400), "" + Time.deltaTime);	
		}
	}
}
